<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formInline" class="el-form query-form el-form--label-right el-form--inline">
      <el-form-item label="运单号">
        <el-input size="small" v-model="formInline.transport_sn" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="交货单日期">
        <el-date-picker v-model="formInlineD.dataValue" type="daterange" align="right" unlink-panels range-separator="-"
          format="yyyy - MM - dd " value-format="yyyy-MM-dd" start-placeholder="开始时间" end-placeholder="结束时间"
          @change="changeDatePicker">
          <!-- :picker-options="pickerOptions" -->
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSearch" icon="el-icon-search">查 询</el-button>
        <el-button size="small" type="primary" @click="handleShow" icon="el-icon-plus">添 加</el-button>
        <el-button size="small" type="primary" @click="uploadDialogVisible = true"
          icon="el-icon-upload2">导入运单</el-button>
        <!-- <el-button size="small" type="default" icon="el-icon-download">
                    <a style="color:#000;text-decoration: none;" href="/muban/sijidaoru.xlsx"
            download="运单导入模板.xlsx">下载模板</a>
                  </el-button> -->
        <el-button size="small" type="primary" icon="el-icon-download">
          <a style="color: #fff;text-decoration: none;" @click="exportReport($event)" href=""
            download="运单导入模板.xlsx">下载模板</a>
        </el-button>
        <el-button size="small" type="primary" @click="onCheck" v-show="is_check" icon="el-icon-upload">批量发布</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="margin-top:30px" row-key="id" @selection-change="handleSelectionChange"
      reserve-selection="true" ref="multipleTable">
      <el-table-column type="selection" width="50" fixed="left" :selectable="selectable"></el-table-column>
      <el-table-column prop="transport_sn" label="运单号"></el-table-column>
      <el-table-column prop="transport_total_amt" label="运单总价（元）"></el-table-column>
      <el-table-column prop="transport_weight" label="重量（吨）"></el-table-column>
      <el-table-column prop="customer_num" label="客户数"></el-table-column>
      <el-table-column prop="dept_name" label="所属DC"></el-table-column>
      <el-table-column prop="delivery_time" label="交货日期"></el-table-column>
      <el-table-column prop="truck_type_name" label="车辆要求"></el-table-column>
      <el-table-column prop="ship_state_name" label="状态"></el-table-column>
      <el-table-column label="操作" :width="300" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handlePush(scope.$index, scope.row)">发布</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="primary" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="default" @click="handleDetail(scope.$index, scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="handleCurrentChange" :current-page="formInline.page" :page-size="formInline.limit"
      :hide-on-single-page="true" layout="total, prev, pager, next" :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="addDialogVisible" width="40%" center :before-close="beforeClose"
      custom-class="center_dislog">
      <el-form ref="editForm" :model="editForm" label-width="130px" :rules="addRules">
        <div class="title_import_title">运单情况</div>
        <el-form-item label="运单号" prop="transport_sn">
          <el-input v-model="editForm.transport_sn" placeholder="请输入运单号" :disabled="!isAdd"></el-input>
        </el-form-item>
        <el-form-item label="运单总价" prop="transport_total_amt">
          <el-input v-model="editForm.transport_total_amt" placeholder="元"></el-input>
        </el-form-item>
        <el-form-item label="交货日期" prop="delivery_time">
          <el-date-picker v-model="editForm.delivery_time" format="yyyy - MM - dd " value-format="yyyy-MM-dd"
            type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="载重量" prop="transport_weight">
          <el-input v-model="editForm.transport_weight" placeholder="吨"></el-input>
        </el-form-item>
        <el-form-item label="发布人联系电话" prop="publish_phone">
          <el-input v-model="editForm.publish_phone" placeholder="请输入发布人联系电话"></el-input>
        </el-form-item>
        <!-- :prop="'domains.' + index + '.value'"
        :rules="{
          required: true, message: '客户不能为空', trigger: 'blur'
        }" -->
        <el-form-item v-for="(domain, index) in editForm.domains" :label="('客户' + (index + 1))" :key="domain.key"
          prop="domains">
          <el-input v-model="domain.customer_name" placeholder="请输入客户名称" style="width:43%"></el-input><el-input
            placeholder="请输入客户地址" v-model="domain.customer_addr" style="width:43%; margin-left:10px"></el-input>
          <el-button icon="el-icon-plus" size="mini" circle @click="addDomain" v-show="index == 0"
            style="margin-left:10px"></el-button>
          <el-button icon="el-icon-minus" size="mini" circle @click.prevent="removeDomain(domain)"
            v-show="index != 0"></el-button>
        </el-form-item>

        <div class="title_import_title">接单要求</div>
        <el-form-item label="车辆类型" prop="truck_type">
          <el-select v-model="editForm.truck_type" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in truckType" :key="index" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送配置" prop="delivery_need">
          <el-checkbox-group v-model="editForm.delivery_need">
            <el-checkbox v-for="item in needData" :label="item.code" :key="item.code">{{ item.name }}
              <el-input v-model="editForm.delivery_need_extend" placeholder="其他内容" v-if="item.code == 5"></el-input>
            </el-checkbox>
          </el-checkbox-group>
          <!-- 其他： -->
        </el-form-item>
        <!-- <el-form-item label="防疫配置" prop="nucleic_acid">
        核酸：
        <el-select v-model="editForm.nucleic_acid" placeholder="请选择" filterable>
          <el-option v-for="(item,index) in TimeType" :key="index" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <br>
        是否要看行程码：
        <el-radio-group v-model="editForm.green_code">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- //导入 -->
    <el-dialog title="导入运单" :visible.sync="uploadDialogVisible" width="40%" center custom-class="center_dislog"
      :before-close="claoseUploadFile">
      <el-upload ref="uploadFile" action="#" accept=".xlsx" :limit="1" :auto-upload="false" :on-remove="handleRemove"
        :http-request="uploadFile">
        <el-button icon="el-icon-plus" size="small" type="primary">选择文件
        </el-button>
        <div slot="tip" class="el-upload__tip">请上传xlsx格式的文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="claoseUploadFile" size="small">取消</el-button>
        <el-button type="primary" :disabled="addDisabled" @click="uploadSubmit" size="small">
          上传</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
import {
  mapState
} from 'vuex'
import {
  waybillList,
  waybillAdd,
  waybillEdit,
  importShipment,
  waybillDele,
  waybillPush,
} from '../../api.js'
export default {
  name: "mangeWayMange",
  data() {
    return {
      isAdd: true,
      isDisabled: false,
      addDialogVisible: false,
      uploadDialogVisible: false,
      addDisabled: false,
      is_check: false,
      breadcrumbName: '',
      breadcrumbPath: '',
      breadcrumbNameP: '',
      tableData: [],
      //查询栏默认展示数据
      formInlineD: {
        dataValue: [],
        value: ''
      },
      formInline: {
        ship_state: 0,
        transport_sn: '',
        start_dt: '',
        end_dt: '',
        page: 1,
        limit: 5
      },
      editForm: {
        transport_sn: '',
        transport_total_amt: '',
        delivery_time: '',
        publish_phone: '',
        transport_weight: '',
        truck_type: '',
        delivery_need: [],
        nucleic_acid: '',
        green_code: -1,
        remark: '',
        delivery_need_extend: '',
        customer_json: [],
        domains: [{
          customer_name: '',
          customer_addr: '',
          customer_sn: '',
        }],
      },
      //分页
      total: 0,
      TimeType: [],
      needData: [],
      truckType: [],
      dialogTitle: "",
      updateFrom: {
        transport_sn: '',
        transport_snArr: '',
      },
      addRules: {
        transport_sn: [{
          required: true,
          message: '请输入运单号',
          trigger: 'blur'
        }],
        truck_type: [{
          required: true,
          message: '请选择车辆类型',
          trigger: 'blur'
        }],
        publish_phone: [{
          required: true,
          message: '请输入发布人联系电话',
          trigger: 'blur'
        }],
        delivery_time: [{
          required: true,
          message: '请选择日期',
          trigger: 'blur'
        }],
        transport_total_amt: [{
          required: true,
          message: '请输入价格',
          trigger: 'blur'
        }],
        transport_weight: [{
          required: true,
          message: '请输入载重量',
          trigger: 'blur'
        }],
        delivery_need: [{
          required: true,
          message: '配送配置',
          trigger: 'change'
        }],
        nucleic_acid: [{
          required: true,
          message: '请选择核酸',
          trigger: 'blur'
        }],
        green_code: [{
          required: true,
          message: '请选择行程码',
          trigger: 'blur'
        }],
      },
    }
  },
  async mounted() {
    this.breadcrumbName = this.$route.query.breadcrumbName
    this.breadcrumbPath = this.$route.query.breadcrumbPath
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP
    var date = new Date;
    var Simdate = this.DateTime(date.getTime() + 24 * 60 * 60 * 1000)
    // this.updateFrom.DeliveryDt = Simdate;
    this.formInlineD.value = Simdate
    this.TimeType = await this.common.getCode(this.baseUrl, 'nucleic_acid', this.Token)
    this.truckType = await this.common.getCode(this.baseUrl, 'truck_type', this.Token)
    this.needData = await this.common.getCode(this.baseUrl, 'delivery_need', this.Token)
    this.getTableDate(this.formInline)
  },
  methods: {
    //获取车辆列表
    getTableDate(searchObj) {
      waybillList(searchObj).then(res => {
        if (res.ErrorCode == 0) {
          this.tableData = res.Data.list
          this.total = res.Data.total
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    //编辑
    handleEdit(index, row) {
      this.isAdd = false
      this.dialogTitle = '编辑';
      this.editForm.id = row.id;
      this.editForm.transport_sn = row.transport_sn;
      this.editForm.transport_total_amt = row.transport_total_amt
      this.editForm.delivery_time = row.delivery_time
      this.editForm.transport_weight = row.transport_weight;
      this.editForm.truck_type = row.truck_type + '';
      this.editForm.delivery_need = row.delivery_need.split(',')
      this.editForm.nucleic_acid = row.nucleic_acid + '',
        this.editForm.green_code = row.green_code;
      this.editForm.remark = row.load_range_max;
      this.editForm.publish_phone = row.publish_phone
      this.editForm.delivery_need_extend = row.delivery_need_extend
      this.editForm.domains = row.customer_data_arr
      this.addDialogVisible = true;
    },
    //表格分页
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.getTableDate(this.formInline)
    },
    //表格查询
    onSearch() {
      this.formInline.page = 1;
      this.getTableDate(this.formInline)
    },
    handleShow(index, row) {
      this.isAdd = true
      this.dialogTitle = "添加"
      this.addDialogVisible = true;
    },
    // //上报
    // handleShow(index, row){
    //   this.addDialogVisible =true;
    //   this.updateFrom.UnifiedTimesNos = row.unifiedTimesNo
    // },
    //查看
    handleDetail(index, row) {
      this.$router.push({
        path: '/waybillMange/way_detail',
        query: {
          id: row.id,
          state: 0,
        }
      })
    },
    formatPassCheck(row, column, cellValue) {
      if (cellValue == 0) {
        return '不要'
      } else if (cellValue == 1) {
        return '要'
      }
    },
    //刪除
    handleDelete(index, row) {
      var _this = this
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
        var data = {
          transport_sn: row.transport_sn,
        }
        waybillDele(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.getTableDate(_this.formInline);
            _this.$message.success("删除成功");
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      }).catch(() => { });
    },

    //提交
    addSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          var _this = this;
          _this.isDisabled = true;
          var dataObj = JSON.parse(JSON.stringify(_this.editForm));
          dataObj.customer_json = JSON.stringify(_this.editForm.domains);
          dataObj.delivery_need = _this.editForm.delivery_need.join(",")
          if (_this.isAdd) {
            waybillAdd(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.addDialogVisible = false
                _this.$refs.editForm.resetFields();
                _this.beforeClose();
                _this.getTableDate(_this.formInline);
                _this.isDisabled = false;
                _this.$message.success("添加成功");
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          } else {
            waybillEdit(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success("编辑成功");
                _this.$refs.editForm.resetFields();
                _this.beforeClose();
                _this.getTableDate(_this.formInline);
                _this.isDisabled = false;
                _this.addDialogVisible = false;
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          }
        }
      })
    },
    selectable(row, index) {
      return row.ship_state == 0
    },
    //发布
    handlePush(index, row) {
      this.updateFrom.transport_sn = row.transport_sn;
      this.typeSn = 1
      this.addSubmitPush();
    },
    onCheck() {
      this.typeSn = 2
      this.addSubmitPush();
    },
    //发布
    addSubmitPush() {
      var _this = this;
      _this.isDisabled = true;
      var data = {
        ship_state: 1
      }
      if (this.typeSn == 1) {
        data.transport_sn = _this.updateFrom.transport_sn
      } else {
        data.transport_sn = _this.updateFrom.transport_snArr
      }
      waybillPush(data).then(res => {
        if (res.ErrorCode == 0) {
          _this.addDialogVisible = false;
          _this.getTableDate(_this.formInline);
          _this.isDisabled = false;
          _this.$message.success("发布成功");
        } else {
          _this.isDisabled = false;
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    removeDomain(item) {
      var index = this.editForm.domains.indexOf(item)
      if (index !== -1) {
        this.editForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.editForm.domains.push({
        customer_name: '',
        customer_addr: '',
        customer_sn: '',
        // key: Date.now()
      });
    },
    beforeClose() {
      this.addDialogVisible = false
      this.editForm = {
        transport_sn: '',
        transport_total_amt: '',
        delivery_time: '',
        transport_weight: '',
        truck_type: '',
        delivery_need: [],
        nucleic_acid: '',
        delivery_need_extend: '',
        publish_phone: '',
        green_code: -1,
        remark: '',
        customer_json: [],
        domains: [{
          customer_name: '',
          customer_addr: '',
          customer_sn: '',
        }],
      }
    },
    formatNorm(row, column, cellValue) {
      return row.loadRangeMin + '~' + row.loadRangeMax
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    changeDatePicker(val) {
      if (val) {
        this.formInline.start_dt = val[0]
        this.formInline.end_dt = val[1]
      } else {
        this.formInline.start_dt = ''
        this.formInline.end_dt = ''
      }
    },

    DateTime(time) {
      var oDate = new Date(time),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth() + 1,
        oDay = oDate.getDate(),
        oTime = oYear + '-' + this.getzf(oMonth) + '-' + this.getzf(oDay);
      return oTime;
    },
    getzf(num) {
      if (parseInt(num) < 10) {
        num = '0' + num;
      }
      return num;
    },
    formatDept(row, column, cellValue) {
      return Array.prototype.join.call(cellValue, '，');
    },
    handleSelectionChange(selection) {
      console.log("selection", selection)
      if (selection.length == 0) {
        this.is_check = false
        this.updateFrom.transport_snArr = ""
      } else {
        this.updateFrom.transport_snArr = ""
        var UnifiedTimesNoArr = [];
        for (var i in selection) {
          UnifiedTimesNoArr.push(selection[i].transport_sn)
          this.updateFrom.transport_snArr = UnifiedTimesNoArr.join(',')
        }
        this.is_check = true
      }
    },
    //下载模板
    exportReport(e) {
      e.target.href = this.baseUrl + 'report/export/shipment_download_xlsx?code=shipment' +
        '&access_token=' + this.Token
    },
    //导入
    uploadSubmit() {
      this.$refs.uploadFile.submit();
    },
    uploadFile(file) {
      const m2 = file.size / 1024 / 1024
      if (m2 > 2) {
        this.$message.error(this.language.prompt_select_xls_file_alert2);
        this.handleRemove()
        return false
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象  
      form.append("file", file.file);
      importShipment(form).then(res => {
        if (res.ErrorCode == 0) {
          this.getTableDate(this.formInline);
          this.$message.success("导入成功");
          this.$refs.uploadFile.clearFiles();
          this.uploadDialogVisible = false
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    claoseUploadFile() {
      this.$refs.uploadFile.clearFiles();
      this.uploadDialogVisible = false
    },
    

  },
  computed: {
    ...mapState({
      baseUrl: state => state.baseUrl,
      Token: state => state.access_token,
    }),
  },
}
</script>

<style scoped>
.title_import_title {
  padding: 0 20px;
  padding-bottom: 30px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.el-dialog__header {
  text-align: center;
}

.el-dialog__footer {
  text-align: center !important;
}
</style>